import Vue from 'vue';
import VueI18n from 'vue-i18n';

import zhCN from './zh-cn.json';
import zhTW from './zh-tw.json';
import en from './en.json';

Vue.use(VueI18n);

export function detectLocale() {
  let locale = (navigator.language || navigator.browserLangugae).toLowerCase();
  switch (true) {
    case /^en.*/i.test(locale):
      locale = 'en';
      break;
    case /^zh-CN/i.test(locale):
      locale = 'zh-cn';
      break;
    case /^zh-TW/i.test(locale):
      locale = 'zh-tw';
      break;
    case /^zh.*/i.test(locale):
      locale = 'zh-cn';
      break;
    default:
      locale = 'zh-cn';
  }

  return locale;
}

const i18n = new VueI18n({
  locale: detectLocale(),
  fallbackLocale: 'zh-cn',
  messages: {
    en: en,
    'zh-cn': zhCN,
    'zh-tw': zhTW,
  },
});

export default i18n;
